#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QWidget>
#include <QString>
#include <QSerialPort>
#include <QTimer>
#include <QPushButton>
#include <QComboBox>
#include <QLineEdit>
#include <QProgressBar>
#include <QLabel>
#include <QTextEdit>
#include <QStatusBar>
#include <QCheckBox>
#include "firmwareupgrader.h"

namespace Ui {
class MainWindow;
}

const quint16 crcTablbeAbs[] = {0x0000,0xCC01,0xD801,0x1400,0xF001,0x3C00,0x2800,0xE401,0xA001,0x6C00,0x7800,0xB401,0x5000,0x9C01,0x8801,0x4400 };

#define BIN_PACK_LEN_MAX 512

class MainWindow : public QWidget
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void onOpenBinFile(void);
    void onDownloadBinFile(void);
    void onRefreshSerialPort(void);
    void onOpenSerialPort(void);
    void onSerialportReadyRead(void);
    void onRespondTimeout(void);
    void writeToSerialPort(const QByteArray &data);
    void onClearLog(void);
    void onDeviceAddressChanged(const QString &address); // Slot for handling device address changes

private:
    // Ui::MainWindow *ui;
    QTimer *m_respondTimer;   //应答超时定时器

    QString m_binPath;
    QSerialPort *m_serialPort;

    QByteArray m_firmwareData;
    qint64 m_bytesWritten;

    bool m_isDowning;
    quint16 m_retryCount;

    quint64 m_binFilePackIndex;    //数据升级包序号

    bool serialPortWrite(const QByteArray data);

    // New UI elements
    QPushButton *pushButton_open_bin;
    QPushButton *pushButton_down_fw;
    QPushButton *pushButton_refresh_sp;
    QPushButton *pushButton_open_sp;
    QPushButton *pushButton_clear_log;
    QPushButton *pushButton_soft_reset; // New button for MCU soft reset
    QPushButton *pushButton_upgrade_reset; // New button for upgrade state machine reset
    QComboBox *comboBox_baudrate;
    QComboBox *comboBox_sp;
    QLineEdit *lineEdit_file_path;
    QLineEdit *lineEdit_device_address; // New line edit for device address
    QLineEdit *lineEdit_crc; // New line edit for CRC
    QProgressBar *progressBar_down;
    QLabel *label_file_size;
    QLabel *label_connection_status;
    QTextEdit *textEdit_log;
    QLabel *label_downloaded_bytes;
    QCheckBox *checkBox_ackRequired; // Checkbox for acknowledgment requirement

    FirmwareUpgrader *m_firmwareUpgrader;
};

#endif // MAINWINDOW_H
